<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import axios from 'axios'

const router = useRouter()
const uploadLoading = ref(false)
const idCardData = ref(null)

// 获取七牛云上传token
const getQiniuToken = async () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('未登录状态')
      return null
    }

    const response = await axios.get('http://localhost:8000/users/qiniu/token/', {
      headers: {
        'Authorization': `Bearer ${token.replace(/^Bearer\s+/i, '').trim()}`
      }
    })

    if (response.data.code === 200) {
      return response.data.data
    } else {
      ElMessage.error(response.data.msg || '获取上传凭证失败')
      return null
    }
  } catch (error) {
    console.error('Get qiniu token error:', error)
    ElMessage.error('获取上传凭证失败')
    return null
  }
}

// 处理文件上传
const handleUpload = async (uploadFile) => {
  try {
    if (!uploadFile || !uploadFile.raw) {
      ElMessage.error('请选择要上传的文件')
      return false
    }

    const file = uploadFile.raw
    uploadLoading.value = true
    
    // 检查文件类型
    const isImage = file.type && file.type.startsWith('image/')
    if (!isImage) {
      ElMessage.error('请上传图片文件')
      return false
    }

    // 检查文件大小（限制为5MB）
    const isLt5M = file.size / 1024 / 1024 < 5
    if (!isLt5M) {
      ElMessage.error('图片大小不能超过 5MB!')
      return false
    }

    // 获取七牛云上传凭证
    const qiniuData = await getQiniuToken()
    if (!qiniuData) {
      return false
    }

    // 准备上传数据
    const formData = new FormData()
    formData.append('token', qiniuData.token)
    formData.append('file', file)

    // 上传到七牛云（使用华北区域的上传域名）
    const uploadResponse = await axios.post('https://upload-z1.qiniup.com', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      timeout: 60000 // 增加到60秒超时
    })

    if (uploadResponse.data && uploadResponse.data.key) {
      ElMessage.success('身份证上传成功')
      // 调用身份证识别接口
      try {
        const imageUrl = `http://swymkvg5u.hb-bkt.clouddn.com/${uploadResponse.data.key}`
        const token = localStorage.getItem('token')
        
        console.log('Uploading image URL:', imageUrl) // 调试日志
        
        const recognizeResponse = await axios.post('http://localhost:8000/users/idcard/recognize/', 
          { image_url: imageUrl },
          {
            headers: {
              'Authorization': `Bearer ${token.replace(/^Bearer\s+/i, '').trim()}`
            },
            timeout: 60000
          }
        )

        console.log('Recognition response:', recognizeResponse.data) // 调试日志

        if (recognizeResponse.data.code === 200 && recognizeResponse.data.data) {
          const idCardInfo = recognizeResponse.data.data
          if (idCardInfo.words_result) {
            ElMessage.success('身份证识别成功')
            showIdCardInfo(idCardInfo)
            
            // 调用实名认证接口
            try {
              const realNameAuthResponse = await axios.post('http://localhost:8000/users/real_name_auth/', 
                {
                  real_name: idCardInfo.words_result['姓名'].words,
                  id_card: idCardInfo.words_result['公民身份号码'].words,
                  id_card_front: imageUrl
                },
                {
                  headers: {
                    'Authorization': `Bearer ${token.replace(/^Bearer\s+/i, '').trim()}`
                  }
                }
              )

              if (realNameAuthResponse.data.code === 200) {
                ElMessage.success('实名认证信息提交成功')
              } else {
                ElMessage.warning(realNameAuthResponse.data.msg || '实名认证提交失败')
              }
            } catch (error) {
              console.error('Real name auth error:', error)
              ElMessage.error(error.response?.data?.msg || '实名认证提交失败')
            }
          } else {
            ElMessage.warning('未能识别出身份证信息，请确保上传的是清晰的身份证正面照片')
            console.warn('No words_result in OCR response:', idCardInfo)
          }
        } else {
          const errorMsg = recognizeResponse.data.msg || '身份证识别失败'
          ElMessage.error(errorMsg)
          console.error('Recognition failed:', recognizeResponse.data)
        }
      } catch (error) {
        console.error('ID card recognition error:', error)
        let errorMsg = '身份证识别失败，请重试'
        
        if (error.response?.data?.msg) {
          errorMsg = error.response.data.msg
        } else if (error.code === 'ECONNABORTED') {
          errorMsg = '请求超时，请重试'
        } else if (error.message) {
          errorMsg = error.message
        }
        
        ElMessage.error(errorMsg)
      }
    } else {
      console.error('Upload response format error:', uploadResponse.data)
      ElMessage.error(uploadResponse.data?.msg || '上传失败：服务器响应格式错误')
    }
  } catch (error) {
    console.error('Upload error:', error)
    if (error.response) {
      console.error('Upload error response:', error.response.data)
      ElMessage.error(error.response.data.error || '上传失败：服务器错误')
    } else if (error.code === 'ECONNABORTED') {
      ElMessage.error('上传超时，请检查网络连接或重试')
    } else {
      ElMessage.error('上传失败，请检查网络连接')
    }
  } finally {
    uploadLoading.value = false
  }
}

const goBack = () => {
  router.back()
}

const showIdCardInfo = (info) => {
  idCardData.value = info
}
</script>

<template>
  <div class="settings-container">
    <div class="settings-header">
      <el-button type="text" @click="goBack" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
      <h1>设置</h1>
    </div>
    
    <div class="settings-content">
      <el-card class="settings-card">
        <template #header>
          <div class="card-header">
            <span>身份认证</span>
          </div>
        </template>
        <div class="upload-section">
          <el-upload
            class="id-card-uploader"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            accept="image/*"
            :on-change="handleUpload"
            :disabled="uploadLoading"
          >
            <template #default>
              <el-button :loading="uploadLoading" type="primary">
                {{ uploadLoading ? '上传中...' : '上传身份证照片' }}
              </el-button>
            </template>
          </el-upload>
          <p class="upload-tip">支持 jpg、png 格式，大小不超过 5MB</p>

          <!-- 添加身份证信息显示部分 -->
          <div v-if="idCardData && idCardData.words_result" class="id-card-info">
            <h3>身份证信息</h3>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="姓名">{{ idCardData.words_result['姓名']?.words || '-' }}</el-descriptions-item>
              <el-descriptions-item label="身份证号">{{ idCardData.words_result['公民身份号码']?.words || '-' }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ idCardData.words_result['性别']?.words || '-' }}</el-descriptions-item>
              <el-descriptions-item label="民族">{{ idCardData.words_result['民族']?.words || '-' }}</el-descriptions-item>
              <el-descriptions-item label="出生">{{ idCardData.words_result['出生']?.words || '-' }}</el-descriptions-item>
              <el-descriptions-item label="住址">{{ idCardData.words_result['住址']?.words || '-' }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
.settings-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.settings-header {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.settings-header h1 {
  color: #333;
  font-size: 24px;
  margin: 0;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 16px;
}

.settings-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.upload-section {
  padding: 20px 0;
  text-align: center;
}

.upload-tip {
  margin-top: 12px;
  color: #909399;
  font-size: 12px;
}

.id-card-info {
  margin-top: 20px;
  text-align: left;
}

.id-card-info h3 {
  margin-bottom: 15px;
  color: #333;
}
</style> 